import React, { useState, useEffect, useImperativeHandle, useRef } from "react";

import style from "./index.module.scss";

interface IProps {
  count?: number;
  text?: string;
  pre?: string;
  next?: string;
  onFinish?: () => void;
  onStart?: () => Promise<any>;
  cref: any;
}

// let timer = null;
export const MCountDown: React.FC<IProps> = ({
  count: defaultCount = 60,
  text = "发送验证码",
  pre = "",
  next = "",
  onFinish = () => {},
  onStart = () => Promise.resolve(),
  cref,
}) => {
  const [count, setCount] = useState(defaultCount);
  const [timer, setTimer] = useState(null);

  useEffect(() => {
    if (count <= 0) {
      init();
    }
  }, [count]);

  const start = (e) => {
    e.preventDefault();
    onStart()
      .then((res) => {
        const t = setInterval(() => {
          setCount((count) => count - 1);
        }, 1000);
        setTimer(t);
      })
      .catch(() => {
        init();
      });
  };
  const init = () => {
    clearInterval(timer);
    setTimer(null);
    setCount(defaultCount);
  };

  useImperativeHandle(cref, () => ({
    init,
  }));

  return (
    <div className={style.wrapper}>
      <button onClick={start} disabled={!!timer} className={style.num}>
        {timer && count >= 0 ? `${pre}${count}${next}` : text}
      </button>
    </div>
  );
};
